package com.apes.scm.masterdata.car.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.repository.CarConfigurationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：配置车型Service
 *
 * @Auther: linwz
 * @Date: 2018/7/26 13:57
 */
@Service("carConfigurationService")
public class CarConfigurationService extends DomainService {

    @Autowired
    CarConfigurationRepository carConfigurationRepository;


    public CarConfiguration save(SimpleRequest request) {
        CarConfiguration carConfiguration = request.getO(CarConfiguration.class);
        return carConfigurationRepository.saveAndFlush(carConfiguration);
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Integer versions = request.get("version");
        CarConfiguration carConfiguration = request.getO(CarConfiguration.class);

        if (carConfiguration == null) throw new RuntimeException("配置车型【" + id + "】在系统中不存在。");
        if (carConfiguration.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        carConfigurationRepository.delete(carConfiguration);
        return "删除成功";
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<CarConfiguration> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return carConfigurationRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /**
     * 判断车型是否停止服务
     * @param id
     * @return
     */
    public boolean isStopService(String id){
        List<CarConfiguration> carConfigurations =
                carConfigurationRepository.findAll(JpaDsl.toCriteriaByEq("id",id,"validFlag","stopService"));
        if(carConfigurations.size() != 0) return true;
        return false;
    }


}
